<template>
  <div>
    <!--顶部-->
    <el-row :gutter="10">
      <el-col :span="5"></el-col>
      <el-col :span="14" style="padding-top: 20px; padding-bottom: 10px">
        <el-card>
          <div class="info_card">
            <div class="info_avatar">
              <el-avatar :size="100" :src="userStore.avatar" />
            </div>
            <div class="info_right">
              <el-text size="large" style="font-weight: bold">{{
                userStore.username
              }}</el-text>
              <el-text
                ><el-icon
                  ><Female v-if="!userInfo.gender" color="red" /><Male
                    v-if="userInfo.gender"
                    color="blue" /></el-icon
                >{{ userInfo.age }}</el-text
              >
            </div>
            <div class="left_button">
              <el-button type="primary" plain @click="showDialog(-1)"
                >编辑头像</el-button
              >
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="5"></el-col>
    </el-row>
    <!--中部-->
    <el-row>
      <el-col :span="5"></el-col>
      <!--左侧菜单-->
      <el-col :span="3">
        <el-card>
          <template #header>
            <div class="card-header">
              <span>个人中心</span>
            </div>
          </template>
          <el-menu
            style="border: 0 !important"
            default-active="1"
            class="el-menu-vertical-demo"
            @select="handleSelect"
          >
            <el-menu-item index="1">
              <el-icon><User /></el-icon>
              <span>个人信息</span>
            </el-menu-item>
            <el-menu-item index="2">
              <el-icon><PieChart /></el-icon>
              <span>数据管理</span>
            </el-menu-item>
            <el-menu-item index="3">
              <el-icon><Star /></el-icon>
              <span>收藏夹</span>
            </el-menu-item>
          </el-menu>
        </el-card>
      </el-col>
      <el-col :span="1"></el-col>
      <!--右侧内容-->
      <el-col :span="10">
        <el-card>
          <!--个人信息-->
          <el-descriptions
            v-if="menuIndex == 1"
            class="margin-top"
            title="个人信息"
            :column="2"
            size="large"
            border
          >
            <template #extra>
              <el-button
                type="primary"
                :icon="Edit"
                @click="showDialog(1)"
                plain
                >编辑</el-button
              >
            </template>
            <el-descriptions-item>
              <template #label>
                <div class="cell-item">
                  <el-icon :style="iconStyle">
                    <user />
                  </el-icon>
                  用户名
                </div>
              </template>
              <el-text>{{ userInfo.username }}</el-text>
            </el-descriptions-item>
            <el-descriptions-item>
              <template #label>
                <div class="cell-item">
                  <el-icon :style="iconStyle">
                    <Key />
                  </el-icon>
                  权限
                </div>
              </template>
              <el-text>{{
                userInfo.role == "admin" ? "管理员" : "普通用户"
              }}</el-text>
            </el-descriptions-item>
            <el-descriptions-item>
              <template #label>
                <div class="cell-item">
                  <el-icon :style="iconStyle">
                    <Female />
                  </el-icon>
                  <el-icon :style="iconStyle">
                    <Male />
                  </el-icon>
                  性别
                </div>
              </template>
              {{ userInfo.gender ? "男" : "女" }}
            </el-descriptions-item>
            <el-descriptions-item>
              <template #label>
                <div class="cell-item">
                  <el-icon :style="iconStyle"><Odometer /></el-icon>
                  年龄
                </div>
              </template>
              {{ userInfo.age }}
            </el-descriptions-item>

            <el-descriptions-item>
              <template #label>
                <div class="cell-item">
                  <el-icon :style="iconStyle"><Avatar /></el-icon>
                  职业
                </div>
              </template>
              {{ userInfo.job }}
            </el-descriptions-item>
            <el-descriptions-item>
              <template #label>
                <div class="cell-item">
                  <el-icon :style="iconStyle"><Orange /></el-icon>
                  体重
                </div>
              </template>
              {{ userInfo.weight }}(kg)
            </el-descriptions-item>
            <el-descriptions-item>
              <template #label>
                <div class="cell-item">
                  <el-icon :style="iconStyle"><Place /></el-icon>
                  身高
                </div>
              </template>
              {{ userInfo.height }}(cm)
            </el-descriptions-item>
            <el-descriptions-item>
              <template #label>
                <div class="cell-item">
                  <el-icon><Timer :style="iconStyle" /></el-icon>
                  注册时间
                </div>
              </template>
              {{ userInfo.time_sign }}
            </el-descriptions-item>
          </el-descriptions>

          <!--数据可视化-->
          <div v-if="menuIndex == 2" class="echarts-container">
            <el-table
              border
              stripe
              :data="tableData"
              style="margin: 10px 0px; width: 100%"
              table-layout="auto"
              fit="false"
            >
              <el-table-column
                prop="range"
                label="期望体重（范围）"
              ></el-table-column>
              <el-table-column label="操作">
                <template #default="scope">
                  <el-form
                    inline="true"
                    label-width="100px"
                    :label-position="left"
                    style="width: 80%; margin-left: 10%"
                  >
                    <el-form-item
                      ><el-button
                        type="primary"
                        size="small"
                        @click="handleEdit(scope.$index, scope.row)"
                        plain
                        >编辑</el-button
                      >
                      <el-button
                        type="primary"
                        size="small"
                        @click="handleRecord()"
                        plain
                        >记录</el-button
                      ></el-form-item
                    >
                    <el-form-item>
                      <el-select
                        v-model="type"
                        placeholder="选择显示模式"
                        size="small"
                        @change="handleChangeType"
                      >
                        <el-option
                          v-for="item in options"
                          :key="item.value"
                          :label="item.label"
                          :value="item.value"
                        ></el-option
                      ></el-select>
                    </el-form-item>
                  </el-form>
                </template>
              </el-table-column>
            </el-table>
            <div class="charts" ref="charts"></div>
          </div>

          <!--收藏-->
          <el-descriptions
            v-if="menuIndex == 3"
            :title="favoriteNum"
            :column="3"
            size="large"
            style="
              width: 90%;
              margin-left: 5%;
              max-height: 700px;
              overflow-y: auto;
            "
          >
            <el-descriptions-item v-for="(item, index) in favoriteList">
              <el-card
                :body-style="{ padding: '10px' }"
                style="height: 300px; width: 200px"
              >
                <img
                  class="image"
                  :src="item.Image_URL"
                  style="width: 180px; height: 200px"
                />
                <div style="padding: 14px">
                  <span style="font-weight: 600; font-size: large">{{
                    item.Dish_name
                  }}</span>
                  <div class="bottom">
                    <el-text truncated
                      >功效：{{ item.Category.slice(1, -1) }}</el-text
                    >
                    <el-button text class="button" type="primary"
                      >详情</el-button
                    >
                  </div>
                </div>
              </el-card>
            </el-descriptions-item>
          </el-descriptions>
        </el-card>
      </el-col>
      <el-col :span="5"></el-col>
    </el-row>
    <el-dialog v-model="isShow" title="编辑头像" width="20%" draggable center>
      <div class="avatar_container">
        <el-upload
          class="avatar-uploader"
          :action="reqUrl"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
        >
          <el-avatar
            v-if="imageUrl"
            :size="70"
            :src="imageUrl"
            @click="editAvatar"
          >
          </el-avatar>
          <el-avatar v-else :icon="UserFilled" :size="70" />
        </el-upload>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancel(-1)">取消</el-button>
          <el-button type="primary" @click="handleEditAvatar"> 确认 </el-button>
        </span>
      </template>
    </el-dialog>

    <el-dialog v-model="isEdit" title="编辑信息" width="40%" center>
      <el-form
        :model="userInfo"
        label-width="100px"
        :label-position="left"
        style="width: 80%; margin-left: 5%"
      >
        <el-form-item label="用户名：">
          <el-input
            v-model="userInfo.username"
            placeholder="请输入用户名"
          ></el-input>
        </el-form-item>
        <el-form-item label="性别：">
          <el-radio-group v-model="userInfo.gender">
            <el-radio label="1" border>男</el-radio>
            <el-radio label="0" border>女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="年龄：">
          <el-input v-model="userInfo.age" placeholder="请输入年龄"
            ><template #suffix>
              <el-icon
                class="el-input__icon"
                style="font-style: normal; margin-right: 10px"
                >岁</el-icon
              >
            </template></el-input
          >
        </el-form-item>
        <el-form-item label="职业：">
          <el-select v-model="userInfo.job" placeholder="请选择你的职业">
            <el-option
              v-for="item in jobList"
              :label="item.label"
              :value="item.label"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="身高：">
          <el-input v-model="userInfo.height" placeholder="请输入身高"
            ><template #suffix>
              <el-icon
                class="el-input__icon"
                style="font-style: normal; margin-right: 10px"
                >cm</el-icon
              >
            </template></el-input
          >
        </el-form-item>
        <el-form-item label="体重：">
          <el-input v-model="userInfo.weight" placeholder="请输入体重"
            ><template #suffix>
              <el-icon
                class="el-input__icon"
                style="font-style: normal; margin-right: 10px"
                >kg</el-icon
              >
            </template>
          </el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancel(1)">取消</el-button>
          <el-button type="primary" @click="handleEditUserInfo">
            提交
          </el-button>
        </span>
      </template>
    </el-dialog>

    <el-dialog v-model="isRange" title="编辑期望值" width="40%" center>
      <el-form :inline="true" style="margin-left: 20%">
        <el-form-item label="最小值">
          <el-input-number
            :precision="2"
            :step="0.1"
            size="middle"
            v-model="newRange.min"
          ></el-input-number>
        </el-form-item>
        <el-form-item label="最大值">
          <el-input-number
            :precision="2"
            :step="0.1"
            size="middle"
            v-model="newRange.max"
          ></el-input-number>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancel(2)">取消</el-button>
          <el-button type="primary" @click="handleEditWeightRange()">
            提交
          </el-button>
        </span>
      </template>
    </el-dialog>

    <el-dialog v-model="isRecord" title="上传体重" width="40%" center>
      <el-form :inline="true" style="margin-left: 15%">
        <el-form-item label="日期">
          <el-date-picker
            v-model="newWeight.date"
            type="date"
            placeholder="日期选择"
            size="middle"
            :disabled-date="disabledDate"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item label="体重(kg)">
          <el-input-number
            :precision="2"
            :step="0.1"
            size="middle"
            v-model="newWeight.weight"
          ></el-input-number>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancel(3)">取消</el-button>
          <el-button type="primary" @click="handleEditWeightRecord()">
            上传
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { onMounted, ref, nextTick, computed } from "vue";
import { Edit } from "@element-plus/icons-vue";
import useUserStore from "@/store/modules/user";
import * as echarts from "echarts";
import {
  reqUserInfo,
  reqGetFavoriteList,
  reqUpdateInfo,
  reqRecordWeight,
  reqGetWeight,
} from "@/api/user";
import { UserFilled } from "@element-plus/icons-vue";
import { ElMessage } from "element-plus";
let userStore = useUserStore();
let charts = ref();
let isShow = ref(false);
const isEdit = ref(false);
const isRange = ref(false);
const isRecord = ref(false);
const imageUrl = ref();
const reqUrl = ref("");
const menuIndex = ref(1);
const favoriteList = ref([]);
const favoriteNum = ref();
const userInfo = ref({});
const dateData = ref([]);
const weightData = ref([]);
const type = ref(1);
const options = [
  {
    value: 0,
    label: "每日",
  },
  {
    value: 1,
    label: "每3日",
  },
  {
    value: 2,
    label: "每月",
  },
];
const newWeight = ref({
  date: "",
  weight: "",
  user_id: userStore.id,
});
const tableData = ref([
  {
    range: "",
    feedback: "反馈",
  },
]);
const jobList = ref([
  {
    id: 0,
    label: "程序员",
  },
  {
    id: 1,
    label: "学生",
  },
  {
    id: 2,
    label: "老师",
  },
  {
    id: 3,
    label: "销售",
  },
  {
    id: 4,
    label: "教师",
  },
  {
    id: 5,
    label: "记者",
  },
  {
    id: 6,
    label: "医生",
  },
  {
    id: 7,
    label: "作家",
  },
  {
    id: 6,
    label: "外卖员",
  },
  {
    id: 7,
    label: "运动员",
  },
]);
const newRange = ref({ max: -1, min: -1 });
onMounted(async () => {
  await getUserInfo();
  await getWeightData();
  getFavoriteList();
});
const handleChangeType = async (val) => {
  switch (val) {
    case 0:
      let res = await reqUserInfo(userStore.id);
      const dates = [];
      const weights = [];
      res.data.weight_change
        .reverse()
        .slice(0, 15)
        .forEach((entry) => {
          const keys = Object.keys(entry);
          const date = keys[0];
          const weight = entry[date];
          dates.push(date);
          weights.push(weight);
        });
      console.log(weights);
      dateData.value = dates.reverse();
      weightData.value = weights.reverse();
      break;
    case 1:
      await getWeightData();
      break;
    case 2:
      let temp = await reqUserInfo(userStore.id);
      // 将数据转换为易于处理的格式
      const flattenedRecords = temp.data.weight_change.flatMap((record) => {
        const [year, month, day] = Object.keys(record)[0].split("-");
        return { year, month, weight: record[Object.keys(record)[0]] };
      });

      // 按年月分组并计算平均值
      const monthlyAverages = {};
      flattenedRecords.forEach((record) => {
        const key = `${record.year}-${record.month}`;
        if (!monthlyAverages[key]) {
          monthlyAverages[key] = { count: 0, total: 0 };
        }
        monthlyAverages[key].count++;
        monthlyAverages[key].total += record.weight;
      });

      // 计算并插入平均值
      Object.entries(monthlyAverages).forEach(([monthYear, group]) => {
        monthlyAverages[monthYear].average = (
          group.total / group.count
        ).toFixed(2);
      });

      // 删除临时统计字段并只保留年月和平均值
      const result = Object.fromEntries(
        Object.entries(monthlyAverages).map(([monthYear, group]) => [
          monthYear,
          group.average,
        ])
      );
      const monthYears = [];
      const averageWeights = [];
      Object.entries(monthlyAverages).forEach(([monthYear, group]) => {
        monthYears.push(monthYear);
        averageWeights.push(parseFloat(group.average));
      });
      dateData.value = monthYears;
      weightData.value = averageWeights;
      console.log(result);
      break;
  }
  initEchart();
};
const getWeightData = async () => {
  let res = await reqGetWeight(userStore.id);
  const dates = [];
  const weights = [];
  res.data.forEach((entry) => {
    const keys = Object.keys(entry);
    const date = keys[0];
    const weight = entry[date];
    dates.push(date);
    weights.push(weight);
  });
  dateData.value = dates;
  weightData.value = weights;
};
const initEchart = () => {
  let mycharts = echarts.init(charts.value);
  let option = {
    backgroundColor: "#fff",
    title: {
      text: "体重变化",
    },
    tooltip: {
      trigger: "axis",
    },
    grid: {
      left: "5%",
      right: "5%",
      bottom: "3%",
      containLabel: true,
    },
    xAxis: {
      type: "category",
      min: "1",
      data: dateData.value,
      boundaryGap: false,
      // 坐标轴线
      axisLine: {
        show: true,
        symbol: ["none", "arrow"],
        lineStyle: {
          color: "#999",
        },
      },
      // 分割线
      splitLine: {
        show: true,
        lineStyle: {
          type: "dashed",
          color: "#e5e5e5",
        },
      },
      name: "时间",
      nameLocation: "middle",
      nameGap: 20,
    },
    yAxis: {
      name: "体重(kg)",
      min: 60,
      max: 80,
      type: "value",
      axisLine: {
        show: true,
        symbol: ["none", "arrow"],
        lineStyle: {
          color: "#999",
        },
      },
      splitLine: {
        lineStyle: {
          type: "dashed",
          color: "#e5e5e5",
        },
      },
    },
    series: [
      {
        name: "体重",
        type: "line",
        color: "#598CFF",
        smooth: true,
        symbol: "circle",
        symbolSize: 14,
        lineStyle: {
          normal: {
            width: 4,
            color: "#598CFF",
          },
        },
        itemStyle: {
          borderColor: "#ffffff",
          borderWidth: 3,
        },
        data: weightData.value,
      },
    ],
  };

  mycharts.setOption(option);
};
const getUserInfo = async () => {
  try {
    const res = await reqUserInfo(userStore.id);
    userInfo.value = res.data;
    tableData.value[0].range = `${res.data.target.min} ~ ${res.data.target.max}kg`;
    newRange.value.max = res.data.target.max;
    newRange.value.min = res.data.target.min;
  } catch (e) {
    console.log(e);
  }
};
const getFavoriteList = async () => {
  console.log(userInfo.value);
  let res = await reqGetFavoriteList({
    id_list: JSON.parse(userInfo.value.favorite),
  });
  favoriteList.value = res.data.meal_list;
  favoriteNum.value = `收藏夹(${res.data.total})`;
};
const handleSelect = (key) => {
  menuIndex.value = key;
  if (menuIndex.value == 2) {
    nextTick(() => {
      console.log(charts.value);
      let mycharts = echarts.init(charts.value);
      let option = {
        backgroundColor: "#fff",
        title: {
          text: "体重变化",
        },
        tooltip: {
          trigger: "axis",
        },
        grid: {
          left: "5%",
          right: "5%",
          bottom: "3%",
          containLabel: true,
        },
        xAxis: {
          type: "category",
          min: "1",
          data: dateData.value,
          boundaryGap: false,
          // 坐标轴线
          axisLine: {
            show: true,
            symbol: ["none", "arrow"],
            lineStyle: {
              color: "#999",
            },
          },
          // 分割线
          splitLine: {
            show: true,
            lineStyle: {
              type: "dashed",
              color: "#e5e5e5",
            },
          },
          name: "时间",
          nameLocation: "middle",
          nameGap: 20,
        },
        yAxis: {
          name: "体重(kg)",
          min: 60,
          max: 80,
          type: "value",
          axisLine: {
            show: true,
            symbol: ["none", "arrow"],
            lineStyle: {
              color: "#999",
            },
          },
          splitLine: {
            lineStyle: {
              type: "dashed",
              color: "#e5e5e5",
            },
          },
        },
        series: [
          {
            name: "体重",
            type: "line",
            color: "#598CFF",
            smooth: true,
            symbol: "circle",
            symbolSize: 14,
            lineStyle: {
              normal: {
                width: 4,
                color: "#598CFF",
              },
            },
            itemStyle: {
              borderColor: "#ffffff",
              borderWidth: 3,
            },
            data: weightData.value,
          },
        ],
      };

      mycharts.setOption(option);
    });
  }
};
const showDialog = (val) => {
  if (val == -1) {
    isShow.value = true;
    imageUrl.value = userStore.avatar;
    reqUrl.value = `http://127.0.1:8000/upload-image/${userStore.id}`;
  } else {
    isEdit.value = true;
  }
};
const handleAvatarSuccess = (response, uploadFile) => {
  console.log(uploadFile);
  imageUrl.value = window.URL.createObjectURL(uploadFile.raw);
  userStore.setState(response.data);
};

const beforeAvatarUpload = (file) => {
  const isJPG = file.type === "image/jpeg";
  const isLt2M = file.size / 1024 / 1024 < 2;
  if (!isJPG) {
    ElMessage.error("头像图片必须是JPG格式!");
    return false;
  } else if (!isLt2M) {
    ElMessage.error("头像图片大小需小于2MB!");
    return false;
  }
  return true;
};

//dialog关闭
const cancel = (val) => {
  if (val == -1) isShow.value = !isShow.value;
  else if (val == 2) isRange.value = !isRange.value;
  else if (val == 3) isRecord.value = !isRecord.value;
  else isEdit.value = !isEdit.value;
};

//提交用户信息编辑
const handleEditUserInfo = async () => {
  const req = {
    username: userInfo.value.username,
    gender: userInfo.value.gender == true ? 1 : 0,
    age: userInfo.value.age,
    job: userInfo.value.job,
    height: userInfo.value.height,
    weight: userInfo.value.weight,
  };
  if (req.username == userStore.username) delete req.username;
  try {
    let res = await reqUpdateInfo(userStore.id, req);
    await getUserInfo();
    userStore.setState(res.data);
    isEdit.value = !isEdit.value;
  } catch (e) {
    console.log(e);
  }
};
const handleEditAvatar = () => {
  isShow.value = !isShow.value;
};
const iconStyle = computed(() => {
  const marginMap = {
    large: "8px",
    default: "6px",
    small: "4px",
  };
  return {
    marginRight: marginMap.default,
  };
});
const handleEdit = () => {
  isRange.value = true;
};
const handleRecord = () => {
  isRecord.value = true;
};
//提交体重范围修改
const handleEditWeightRange = async () => {
  const req = {
    target: newRange.value,
  };
  try {
    let res = await reqUpdateInfo(userStore.id, req);
    ElMessage.success("修改成功！");
    await getUserInfo();
  } catch (e) {
    ElMessage.error("修改失败！");
  }
  isRange.value = false;
};
//体重上传
const disabledDate = (time) => {
  return time.getTime() > Date.now();
};
const handleEditWeightRecord = async () => {
  newWeight.value.user_id = parseInt(userStore.id);
  let res = await reqRecordWeight(newWeight.value);
  if (res.code == 200) {
    ElMessage.success("上传成功");
    isRecord.value = false;
  } else {
    ElMessage.error("上传失败");
  }
};
</script>

<style lang="scss" scoped>
.info_card {
  display: flex;
  flex-direction: row;
  .info_avatar {
    padding-right: 10px;
  }
  .info_right {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
  }
  .left_button {
    margin-left: auto;
  }
}
.el-menu-item {
  justify-content: center;
}
.el-descriptions {
  margin-top: 20px;
}
.cell-item {
  display: flex;
  align-items: center;
}
.margin-top {
  margin-top: 20px;
}
.charts {
  width: 100%;
  height: 500px;
}

.bottom {
  margin-top: 13px;
  line-height: 12px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.button {
  padding: 0;
  min-height: auto;
}
.avatar_container {
  display: flex;
  justify-content: center;
  align-items: center;
  position: relative;
}
</style>
